import { batchListAll } from "@/api/business/registerNeed";

/**
 * 获取批次数据的通用方法
 * @param {Object} options 配置选项
 * @param {boolean} options.setCurrentYear 是否设置当前年份，默认为true
 * @param {boolean} options.autoSelectBatch 是否自动选择最近的批次，默认为true
 * @param {string} options.yearField 年份字段名，默认为'registerYear'
 * @param {string} options.batchField 批次字段名，默认为'batchName'
 * @returns {Promise<Object>} 返回包含批次列表和查询参数的对象
 */
export async function getBatchData(options = {}) {
  const {
    setCurrentYear = true,
    autoSelectBatch = true,
    yearField = "registerYear",
    batchField = "batchName",
  } = options;

  try {
    // 从接口获取所有批次数据
    const response = await batchListAll();
    const allBatches = response.data || [];

    // 设置批次下拉选项（包含所有批次，倒序排列）
    const registerBatchList = [
      { name: "所有月份", value: "" },
      ...allBatches.reverse().map((item) => ({
        name: item.registerMonth,
        value: item.registerMonth,
      })),
    ];

    // 默认选中批次只能从3、6、9、12月中选择
    const defaultBatches = [
      { id: 1, batch: "3月" },
      { id: 2, batch: "6月" },
      { id: 3, batch: "9月" },
      { id: 4, batch: "12月" },
    ];

    const queryParams = {};

    // 设置当前年份
    if (setCurrentYear) {
      const currentYear = new Date().getFullYear();
      queryParams[yearField] = currentYear.toString();
    }

    // 自动选择最近的批次（只从3、6、9、12月中选择）
    // if (autoSelectBatch && defaultBatches.length > 0) {
    //   const now = new Date();
    //   const currentMonth = now.getMonth() + 1; // 当前月份 (1-12)
    //   let closestBatch = null;
    //   let minDiff = 12; // 最大月份差为11

    //   defaultBatches.forEach((batch) => {
    //     // 从批次名称中提取月份数字 (如 "3月" -> 3)
    //     const month = parseInt(batch.batch);
    //     if (isNaN(month)) return; // 如果解析失败则跳过

    //     // 计算月份差值（考虑跨年情况）
    //     let diff = Math.abs(month - currentMonth);
    //     diff = Math.min(diff, 12 - diff); // 取最小差值（考虑跨年）

    //     if (diff < minDiff) {
    //       minDiff = diff;
    //       closestBatch = batch;
    //     } else if (diff === minDiff && closestBatch) {
    //       // 如果差值相同，选择月份较大的（即更接近年末的）
    //       const currentBatchMonth = parseInt(closestBatch.batch);
    //       if (month > currentBatchMonth) {
    //         closestBatch = batch;
    //       }
    //     }
    //   });

    //   if (closestBatch) {
    //     queryParams[batchField] = closestBatch.batch;
    //   }
    // }

    return {
      registerBatchList,
      queryParams,
      allBatches,
      defaultBatches,
    };
  } catch (error) {
    console.error("获取批次数据失败:", error);
    // 如果接口调用失败，使用默认的硬编码数据
    const fallbackBatchList = [
      { name: "所有月份", value: "" },
      { name: "3月", value: "3月" },
      { name: "6月", value: "6月" },
      { name: "9月", value: "9月" },
      { name: "12月", value: "12月" },
    ];

    const queryParams = {};
    if (setCurrentYear) {
      const currentYear = new Date().getFullYear();
      queryParams[yearField] = currentYear.toString();
    }

    return {
      registerBatchList: fallbackBatchList,
      queryParams,
      allBatches: [],
      defaultBatches: [
        { id: 1, batch: "3月" },
        { id: 2, batch: "6月" },
        { id: 3, batch: "9月" },
        { id: 4, batch: "12月" },
      ],
    };
  }
}

/**
 * 为Vue组件提供的批次数据混入方法
 * @param {Object} options 配置选项
 * @returns {Promise<void>}
 */
export async function setupBatchData(vueInstance, options = {}) {
  const result = await getBatchData(options);

  // 设置批次列表
  vueInstance.registerBatchList = result.registerBatchList;

  // 合并查询参数
  Object.assign(vueInstance.queryParams, result.queryParams);

  return result;
}

/**
 * 获取批次月份数字
 * @param {string} batchName 批次名称，如"3月"
 * @returns {number} 月份数字
 */
export function getBatchMonth(batchName) {
  if (!batchName) return null;
  const month = parseInt(batchName);
  return isNaN(month) ? null : month;
}

/**
 * 验证批次时间范围
 * @param {string} durationStartDate 进修开始日期
 * @param {Array} batchList 批次列表
 * @returns {Object} 验证结果
 */
export async function validateBatchTimeRange(
  durationStartDate,
  batchList = null
) {
  try {
    let batches = batchList;
    if (!batches) {
      const response = await batchListAll();
      batches = response.data || [];
    }

    // 获取当前科室对应的批次信息
    const currentBatch = batches.find((batch) => {
      // 根据进修期限的月份匹配批次
      const month = new Date(durationStartDate).getMonth() + 1;
      const batchMonth = getBatchMonth(batch.batchName);
      return batchMonth === month;
    });

    if (currentBatch) {
      // 检查当前时间是否在批次的开始和结束时间范围内
      const currentDate = new Date();
      let startDate, endDate;

      // 解析批次开始时间，兼容苹果浏览器
      if (currentBatch.startDate) {
        if (currentBatch.startDate.includes("/")) {
          startDate = new Date(currentBatch.startDate.replace(/\//g, "-"));
        } else {
          startDate = new Date(currentBatch.startDate);
        }
      }

      // 解析批次结束时间，兼容苹果浏览器
      if (currentBatch.endDate) {
        if (currentBatch.endDate.includes("/")) {
          endDate = new Date(currentBatch.endDate.replace(/\//g, "-"));
        } else {
          endDate = new Date(currentBatch.endDate);
        }
      }

      if (startDate && endDate) {
        const isInRange = currentDate >= startDate && currentDate <= endDate;
        return {
          isValid: isInRange,
          currentBatch,
          startDate,
          endDate,
          currentDate,
        };
      }
    }

    return {
      isValid: false,
      currentBatch: null,
      message: "未找到对应的批次信息",
    };
  } catch (error) {
    console.error("验证批次时间范围失败:", error);
    return {
      isValid: false,
      error: error.message,
    };
  }
}
